import json
import io
import sys
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from myapp.elecmain.hardware_docking import get_password
from myapp.elecmain.manage import merchant_agent, transfer_hardware, ordinary_merchants, add_hardware, \
    query_hardware, order_manage, add_Service, Service_find, register, modify, remove_user, pay_paypal, pay_wx, addpay, \
    delete_merchants, add_merchants, delete_store, get_store, delete_service, modify_service, add_store


# 订单添加
# 支付类型
@require_http_methods(["POST"])
@csrf_exempt
def pay_add_view(request):
    icon = request.POST.get('icon')
    id = request.POST.get('id')
    money = request.POST.get('money')
    userId = request.POST.get('userId')
    moneyType = request.POST.get('moneyType')
    response = addpay(icon, money, id, userId, moneyType)
    if response.get('status') == 'success':
        return JsonResponse(response)
    else:
        return JsonResponse(response, status=400)


# 支付类型
import json
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt

@require_http_methods(["POST"])
@csrf_exempt
def pay_view(request):
    try:
        # 解析 JSON 数据
        data = json.loads(request.body)
        icon = data.get('icon')
        money = data.get('money')
        userId = data.get('userId')
        moneyType = data.get('moneyType')
    except json.JSONDecodeError:
        return JsonResponse({'status': 'error', 'message': 'Invalid JSON'}, status=400)

    payment_methods = {
        "RMB": pay_paypal,
        "USD": pay_wx
    }
    payment_function = payment_methods.get(moneyType)

    if payment_function:
        response = payment_function(icon, money, userId, moneyType)
        if response.get('status') == 'success':
            return JsonResponse(response)
        else:
            return JsonResponse(response, status=400)
    else:
        # 处理未知的 moneyType
        return JsonResponse({'status': 'error', 'message': 'Unsupported currency type'}, status=404)



# 注册
@require_http_methods(["POST"])
@csrf_exempt
def register_view(request):
    if request.method == 'POST':
        # 获取表单数据
        user_id = request.POST.get('user_id')
        userName = request.POST.get('userName')
        password = request.POST.get('password')

        # 调用登录函数
        response = register(user_id, userName, password)

        # 根据 login 函数的返回值生成响应
        if response['status'] == 'success':
            return JsonResponse(response)
        else:
            return JsonResponse(response, status=400)


# 修改密码
@require_http_methods(["POST"])
@csrf_exempt
def modify_view(request):
    if request.method == 'POST':
        # 获取表单数据
        user_id = request.POST.get('user_id')
        userName = request.POST.get('userName')
        password = request.POST.get('password')

        # 调用登录函数
        response = modify(user_id, userName, password)

        # 根据 login 函数的返回值生成响应
        if response['status'] == 'success':
            return JsonResponse(response)
        else:
            return JsonResponse(response, status=400)


# 删除用户
@require_http_methods(["POST"])
@csrf_exempt
def remove_user_view(request):
    if request.method == 'POST':
        # 获取表单数据
        user_id = request.POST.get('user_id')
        # 调用登录函数
        response = remove_user(user_id)
        # 根据 login 函数的返回值生成响应
        if response['status'] == 'success':
            return JsonResponse(response)
        else:
            return JsonResponse(response, status=400)


# 查询商家
@require_http_methods(["GET"])
@csrf_exempt
def get_allmerchants(request):
    data = ordinary_merchants()
    list_zy1 = []
    for data1 in data:
        row = {
            "Merchant_id": data1[0],
            "Merchant_name": data1[1],
            "Address": data1[2],
            "Local_currency": data1[3],
            "My_profit": data1[4],
        }
        list_zy1.append(row)
    print(list_zy1)
    return JsonResponse(list_zy1, safe=False)


# 删除商家
@require_http_methods(["POST"])
@csrf_exempt
def delete_merchants_view(request):
    if request.method == 'POST':
        try:
            # 解析 JSON 数据
            data = json.loads(request.body)
            Merchant_id = data.get('Merchant_id')

            if not Merchant_id:
                return JsonResponse({'error': '缺少商家ID'}, status=400)

            delete_merchants(Merchant_id)
            return HttpResponse('操作成功', status=200)

        except json.JSONDecodeError:
            return JsonResponse({'error': '无效的 JSON'}, status=400)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': '无效的请求方法'}, status=405)


# 添加商家
@require_http_methods(["POST"])
@csrf_exempt
def add_merchants_view(request):
    if request.method == 'POST':
        Merchant_name = request.POST.get('Merchant_name')
        Address = request.POST.get('Address')
        Local_currency = request.POST.get('Local_currency')

        missing_fields = []
        if not Merchant_name:
            missing_fields.append('商家名称')
        if not Address:
            missing_fields.append('地址')
        if not Local_currency:
            missing_fields.append('货币')

        if missing_fields:
            return JsonResponse({'error': '缺少以下字段: ' + ', '.join(missing_fields)}, status=400)

        try:
            add_merchants(Merchant_name, Address, Local_currency)
            return HttpResponse('操作成功', status=200)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': '无效的请求方法'}, status=405)


# 商家代理管理
@require_http_methods(["POST"])
@csrf_exempt
def upload_view(request):
    if request.method == 'POST':
        # 获取表单数据
        mer_id = request.POST.get('Merchant ID')
        name = request.POST.get('Merchant name')
        level = request.POST.get('Agent Level')
        original_id = request.POST.get('Original ID')

        # 处理数据（例如调用 merchant_agent 函数）
        merchant_agent(mer_id, name, level, original_id)

        # 返回操作成功并包含接收到的数据
        response_data = {
            'Merchant ID': mer_id,
            'Merchant name': name,
            'Agent Level': level,
            'Original ID': original_id
        }
        return HttpResponse(json.dumps(response_data), content_type='application/json', status=200)


# 添加门店
@require_http_methods(["POST"])
@csrf_exempt
def add_store_view(request):
    if request.method == 'POST':
        # 获取表单数据
        Store_id = request.POST.get('Store_id')
        Store_name = request.POST.get('Store_name')
        Address = request.POST.get('Address')
        Longitude = request.POST.get('Longitude')
        Latitude = request.POST.get('Latitude')
        try:
            add_store(Store_id, Store_name, Address, Longitude, Latitude)
            return HttpResponse('操作成功', status=200)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    return JsonResponse({'error': '无效的请求方法'}, status=405)


# 删除门店
@require_http_methods(["POST"])
@csrf_exempt
def delete_store_view(request):
    if request.method == 'POST':
        # 解析 JSON 数据
        data = json.loads(request.body)
        store_id = data.get('store_id')

        if not store_id:
            return JsonResponse({'error': '缺少商家ID'}, status=400)

        try:
            delete_store(store_id)
            return HttpResponse('操作成功', status=200)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': '无效的请求方法'}, status=405)


# 查询门店
@require_http_methods(["GET"])
@csrf_exempt
def get_store_view(request):
    data = get_store()
    list_zy1 = []
    for data1 in data:
        row = {
            "Store_id": data1[0],
            "Store_name": data1[1],
            "Address": data1[2],
            "Longitude": data1[3],
            "Latitude": data1[4],
        }
        list_zy1.append(row)
    print(list_zy1)
    return JsonResponse(list_zy1, safe=False)


# 查找硬件
@require_http_methods(["POST"])
@csrf_exempt
def seek_hardware(request):
    if request.method == 'POST':
        try:
            # 解析 JSON 请求体
            data = json.loads(request.body)
            Bind_merchant = data.get('Bind_merchant')
            # 调用 query_hardware 函数
            query_hardware(Bind_merchant)

            return HttpResponse('操作成功', status=200)

        except json.JSONDecodeError:
            return HttpResponse('Invalid JSON', status=400)
        except Exception as e:
            return HttpResponse(f'出现错误: {e}', status=500)


# 添加硬件
@require_http_methods(["POST"])
@csrf_exempt
def get_hardware(request):
    if request.method == 'POST':
        # 获取表单数据
        Hardware_QR_code = request.POST.get('Hardware_QR_code')
        Hardware_type = request.POST.get('Hardware_type')
        Bind_merchant = request.POST.get('Bind_merchant')
        Store_id = request.POST.get('Store_id')
        add_hardware(Hardware_QR_code, Hardware_type, Bind_merchant, Store_id)
        # 返回操作成功并包含接收到的数据
        return HttpResponse('操作成功', status=200)


# 查询订单
@require_http_methods(["GET"])
@csrf_exempt
def get_order(request):
    data = order_manage()
    list_zy1 = []
    for data1 in data:
        row = {
            "Order_id": data1[0],
            "Service": data1[1],
            "HardWare_type": data1[2],
            "Amount": data1[3],
            "Time": data1[4],
            "Store_name": data1[5],
            "Hardware_code": data1[6],
            "Merchant": data1[7],
            "My_profit": data1[8],
        }
        list_zy1.append(row)
    print(list_zy1)
    return JsonResponse(list_zy1, safe=False)


# 查询服务
@require_http_methods(["GET"])
@csrf_exempt
def get_service(request):
    data = Service_find()
    list_zy1 = []
    for data1 in data:
        row = {
            "Service_id": data1[0],
            "Hardware_type": data1[1],
            "Service": data1[2],
            "Price": data1[3],
            "Store_id": data1[4],
        }
        list_zy1.append(row)
    print(list_zy1)
    return JsonResponse(list_zy1, safe=False)


# 添加服务
@require_http_methods(["POST"])
@csrf_exempt
def increase_service(request):
    if request.method == 'POST':
        # 获取表单数据
        Service_id = request.POST.get('Service_id')
        Service = request.POST.get('Service')
        Price = request.POST.get('Price')
        Hardware_type = request.POST.get('Hardware_type')
        Store_id = request.POST.get('Store_id')
        add_Service(Service_id, Service, Price, Hardware_type, Store_id)
        # 返回操作成功并包含接收到的数据
        return HttpResponse('操作成功', status=200)


# 删除服务
@require_http_methods(["POST"])
@csrf_exempt
def delete_service_view(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        service_id = data.get('Service_id')

        if not service_id:
            return JsonResponse({'error': '缺少服务ID'}, status=400)

        try:
            delete_service(service_id)
            return HttpResponse('操作成功', status=200)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': '无效的请求方法'}, status=405)


# 修改服务
@require_http_methods(["POST"])
@csrf_exempt
def modify_service_view(request):
    if request.method == 'POST':
        Service_id = request.POST.get('service_id')
        Hardware_type = request.POST.get('Hardware_type')
        Service = request.POST.get('Service')
        Price = request.POST.get('Price')
        Store_id = request.POST.get('Store_id')
        if not Service_id:
            return JsonResponse({'error': '缺少服务编号'}, status=400)

        try:
            modify_service(Service_id, Hardware_type, Service, Price, Store_id)
            return HttpResponse({'code': 1, 'message': 'success',}, status=200)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)

    return JsonResponse({'error': '无效的请求方法'}, status=405)


# 获取密码
@require_http_methods(["POST"])
@csrf_exempt
def get_password_view(request):
    if request.method == 'POST':
        try:
            # 解析 JSON 请求体
            data = json.loads(request.body)
            deviceid = data.get('device_id')
            times_value = data.get('times_value')
            print(deviceid, times_value)
            # 获取密码
            password = get_password(deviceid, times_value)

            return JsonResponse({
                'code': 1,
                'message': 'success',
                'data': {'password': password}
            }, status=200)
        except json.JSONDecodeError:
            return JsonResponse({'code': 0, 'message': 'Invalid JSON'}, status=400)
        except Exception as e:
            return JsonResponse({'code': 0, 'message': f'出现错误: {e}'}, status=500)
